/*

Copyright (C) 2007 Manfred Gschweidl (manfred.gschweidl@students.fhv.at)

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

*/

#include <octave/oct.h>

#include <sstream>
#include <string>


#include "globuscpp/CredManager.h"

using namespace std;
using namespace globus_common;

static void usage() {
	error("gt_createproxy('password'[, 'myproxy server'])");
}

DEFUN_DLD(gt_createproxy, 
          args, 
          , 
          "Create a proxy certificate."
          ) 
{	
	int argNum;
	string password;
	string myproxyServer;
	bool success = false;
	
	// arg(0) => url
	argNum = args.length();

	if (argNum < 1)  {
		error("Invalid arguments.");	
		usage();
		return octave_value(false);
	}

	// parse args
	password = 	args(0).string_value();
	if (argNum > 1) {
		myproxyServer = args(1).string_value();
	}
	
	if(password.empty()) {
		cerr << "No password provided." << endl;
		return octave_value(false);
	}
	
	if(argNum >= 2 && myproxyServer.empty()) {
		cerr << "No myproxy server provided." << endl;
		return octave_value(false);
	}
	
	// check for existing certificate or aquire one
	CredManager credMgr;	                                            
	if ( !credMgr.hasCredential() ) {
		if(argNum == 1) {		
			success = credMgr.acquireCredential(password);
		} else {
			success = credMgr.acquireCredentialMyProxy(myproxyServer, password);
		}
		if(!success) {
			return octave_value(false);
		}
	} else {
		cout << "Certificate already exists." << endl;
	}
	
	return octave_value(true);
}
